package com.lottery.material.controller.admin.promotion;

import com.lottery.material.common.EnumInfo;
import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.enumeration.promotion.PromotionRuleConfigEnum;
import com.lottery.material.pojo.page.Page;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.pojo.promotion.PromotionRuleConfig;
import com.lottery.material.pojocustom.promotion.PromotionRuleConfigCustom;
import com.lottery.material.service.admin.promotion.PromotionRuleConfigService;
import com.lottery.material.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description：推广规则配置Controller
 * Created by 朱正磊 on 2019-04-13 20:22
 */
@Controller("adminPromotionRuleConfigController")
@RequestMapping("/admin/promotionRuleConfig")
public class PromotionRuleConfigController extends BaseController {

    //菜单地址，用于权限控制
    private String menuUrl = "admin/promotionRuleConfig/list";

    private final PromotionRuleConfigService promotionRuleConfigService;

    @Autowired
    public PromotionRuleConfigController(PromotionRuleConfigService promotionRuleConfigService) {
        this.promotionRuleConfigService = promotionRuleConfigService;
    }

    /**
     * description：分页列表
     * user 朱正磊
     * time 2019-04-17 15:06
     * @param page 分页对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/list")
    public ModelAndView listPage(Page page, Map<String, Object> map) {
        //分页对象设置页面请求参数
        PageData pd = getPageData();
        PdUtil.rePut(pd);
        page.setPd(pd);

        //查询分页列表
        List<PromotionRuleConfigCustom> list = promotionRuleConfigService.findCustomListPage(page);
        map.put("list", list);
        map.put("pd", pd);
        map.put("QX", Jurisdiction.getHC());

        //推广类型（1：圈子内文章推广；2：群聊内文章推广）
        List<EnumInfo> promotionTypeList = EnumUtil.getEnumInfoList(
                PromotionRuleConfigEnum.PROMOTION_TYPE, PromotionRuleConfigEnum.class);
        map.put("promotionTypeList", promotionTypeList);

        return new ModelAndView("promotion/promotionRuleConfig/listPage", map);
    }

    /**
     * description：详情页面
     * user 朱正磊
     * time 2019-04-17 16:20
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/detailPage")
    public ModelAndView detailPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {//判断是否有查看权限
            return null;
        }

        //根据主键查询扩展类
        PromotionRuleConfigCustom promotionRuleConfig = promotionRuleConfigService.findCustomById(id);
        map.put("promotionRuleConfig", promotionRuleConfig);

        return new ModelAndView("promotion/promotionRuleConfig/detailPage", map);
    }

    /**
     * description：添加页面
     * user 朱正磊
     * time 2019-04-17 16:26
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/addPage")
    public ModelAndView addPage(Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {//判断是否有添加权限
            return null;
        }

        //推广类型（1：圈子内文章推广；2：群聊内文章推广）
        List<EnumInfo> promotionTypeList = EnumUtil.getEnumInfoList(
                PromotionRuleConfigEnum.PROMOTION_TYPE, PromotionRuleConfigEnum.class);
        /*for (EnumInfo enumInfo : promotionTypeList) {
            Integer type = (Integer) enumInfo.getValue();
            PromotionRuleConfig config = promotionRuleConfigService.findByType(type);
            if (AssertUtil.isNotEmpty(config)) {
                promotionTypeList.remove(enumInfo);
            }
        }*/
        Iterator<EnumInfo> iterator = promotionTypeList.iterator();
        while (iterator.hasNext()) {
            EnumInfo enumInfo = iterator.next();
            Integer type = (Integer) enumInfo.getValue();
            PromotionRuleConfig config = promotionRuleConfigService.findByType(type);
            if (AssertUtil.isNotEmpty(config)) {
                iterator.remove();
            }
        }
        map.put("promotionTypeList", promotionTypeList);

        //添加请求地址
        map.put("actionUrl", "admin/promotionRuleConfig/add");

        return new ModelAndView("promotion/promotionRuleConfig/editPage", map);
    }

    /**
     * description：添加
     * user 朱正磊
     * time 2019-04-17 16:39
     * @param promotionRuleConfig 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/add")
    public ModelAndView add(PromotionRuleConfig promotionRuleConfig, Map<String, Object> map) {
        Integer flag = promotionRuleConfigService.add(promotionRuleConfig);
        if (Objects.equals(flag, 0)) { //添加失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：修改页面
     * user 朱正磊
     * time 2019-04-17 16:48
     * @param id 主键
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/editPage")
    public ModelAndView editPage(Integer id, Map<String, Object> map) {
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {//判断是否有修改权限
            return null;
        }

        //根据主键查询扩展类
        PromotionRuleConfigCustom promotionRuleConfig = promotionRuleConfigService.findCustomById(id);
        map.put("promotionRuleConfig", promotionRuleConfig);

        //推广类型（1：圈子内文章推广；2：群聊内文章推广）
        List<EnumInfo> promotionTypeList = EnumUtil.getEnumInfoList(
                PromotionRuleConfigEnum.PROMOTION_TYPE, PromotionRuleConfigEnum.class);
        /*for (EnumInfo enumInfo : promotionTypeList) {
            Integer type = (Integer) enumInfo.getValue();
            if (!Objects.equals(type, promotionRuleConfig.getPromotionType())) {
                PromotionRuleConfig config = promotionRuleConfigService.findByType(type);
                if (AssertUtil.isNotEmpty(config)) {
                    ListUtil.removeParamsInList(promotionTypeList, enumInfo);
                }
            }
        }*/
        Iterator<EnumInfo> iterator = promotionTypeList.iterator();
        while (iterator.hasNext()) {
            EnumInfo enumInfo = iterator.next();
            Integer type = (Integer) enumInfo.getValue();
            if (!Objects.equals(type, promotionRuleConfig.getPromotionType())) {
                PromotionRuleConfig config = promotionRuleConfigService.findByType(type);
                if (AssertUtil.isNotEmpty(config)) {
                    iterator.remove();
                }
            }
        }
        map.put("promotionTypeList", promotionTypeList);

        //修改请求地址
        map.put("actionUrl", "admin/promotionRuleConfig/edit");

        return new ModelAndView("promotion/promotionRuleConfig/editPage", map);
    }

    /**
     * description：修改
     * user 朱正磊
     * time 2019-04-17 16:58
     * @param promotionRuleConfig 对象
     * @param map 响应数据Map
     * @return 返回模型视图
     */
    @RequestMapping("/edit")
    public ModelAndView edit(PromotionRuleConfig promotionRuleConfig, Map<String, Object> map) {
        Integer flag = promotionRuleConfigService.updateById(promotionRuleConfig);
        if (Objects.equals(flag, 0)) { //修改失败
            throw new RuntimeException(ResultEnum.STATUS_PERSISTENT_OPERATE_SQL_FAIL.getMessage());
        } else {
            map.put("msg","success");
            return new ModelAndView("save_result", map);
        }
    }

    /**
     * description：验证当前所有类别是否均已存在对应规则
     * user 朱正磊
     * time 2019-04-30 14:43
     * @return 返回响应对象
     */
    @RequestMapping("/validateAdd")
    @ResponseBody
    public ResponseResult validateAdd() {
        Boolean flag = false;
        PromotionRuleConfigEnum[] enumConstants = PromotionRuleConfigEnum.class.getEnumConstants();
        for (PromotionRuleConfigEnum promotionRuleConfigEnum : enumConstants) {
            Integer type = (Integer) promotionRuleConfigEnum.getValue();
            PromotionRuleConfig promotionRuleConfig = promotionRuleConfigService.findByType(type);
            if (AssertUtil.isEmpty(promotionRuleConfig)) { //如果有一个类别没有配置规则，就跳出循环
                flag = true;
                break;
            }
        }
        if (flag) {
            return ResponseResult.buildResult(400); //至少有一个类别没有配置规则
        } else {
            return ResponseResult.buildResult(200); //当前所有类别均已存在对应规则
        }
    }

}
